//
//  BAEditDetailVCView.m
//  BabyAlbum
//
//  Created by master on 17/2/27.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAEditDetailViewNode.h"
#import "BAAlbumListLayout.h"
#import "TZImagePickerController.h"
#import "MWPhotoBrowser.h"
#import "BAResourceNode.h"
#import "WSDatePickerView.h"
#import "BAResourceCell.h"
#import "BAFooterView.h"
#import "BACollectionView.h"
@interface BAEditDetailViewNode () <ASEditableTextNodeDelegate,TZImagePickerControllerDelegate,UIActionSheetDelegate,MWPhotoBrowserDelegate,UICollectionViewDelegate,UICollectionViewDataSource>


@property (nonatomic, strong) NSMutableArray<BAAlbumItem *> *resourceList;
@property (nonatomic, strong) NSMutableArray <MWPhoto *> *photos;
@property (nonatomic, strong) BAFooterView *footerView;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) BOOL showAddButton;
//@property (nonatomic, strong) UIView *backgroundView;

@end


@implementation BAEditDetailViewNode

- (instancetype)initWithData:(BAAlbumModel *)model {
    self = [super init];
    self.albumModel = model;
    _showAddButton = model.resourceList.count < 20;
     [[XYKeyboardHelper sharedInstance] enableKeyboardHelper];
    return self;
}

- (void)dealloc {
     [[XYKeyboardHelper sharedInstance] disableKeyboardHelper];
}

- (UILongPressGestureRecognizer *)longPress {
    if(!_longPress) {
        _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showEdit:)];
        _longPress.minimumPressDuration = 1;
        
    }
    return _longPress;
}

- (void)showEdit:(UILongPressGestureRecognizer *)ges {
    switch (_longPress.state) {
        case UIGestureRecognizerStateBegan: {
            {
                NSIndexPath *selectIndexPath = [self.collectionView indexPathForItemAtPoint:[_longPress locationInView:self.collectionView]];
                // 找到当前的cell
//                BAResourceNode *cellNode = (BAResourceNode *)[self.collectionView cellForItemAtIndexPath:selectIndexPath];
                // 定义cell的时候btn是隐藏的, 在这里设置为NO
//                [cell.btnDelete setHidden:NO];
                [self.collectionView beginInteractiveMovementForItemAtIndexPath:selectIndexPath];
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            [self.collectionView updateInteractiveMovementTargetPosition:[ges locationInView:_longPress.view]];
            break;
        }
        case UIGestureRecognizerStateEnded: {
            [self.collectionView endInteractiveMovement];
            break;
        }
        default: [self.collectionView cancelInteractiveMovement];
            break;
    }

}
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == self.resourceList.count) {
        return NO;
    }
    //返回YES允许其item移动
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canFocusItemAtIndexPath:(NSIndexPath *)indexPath {
    if(self.resourceList.count == indexPath.row) {
        return NO;
    }
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    if(destinationIndexPath.row >= self.resourceList.count || sourceIndexPath.row >= self.resourceList.count) {
        [self.collectionView moveItemAtIndexPath:destinationIndexPath toIndexPath:sourceIndexPath];
        return;
    }
    //取出源item数据
//    id objc = [self.resourceList objectAtIndex:sourceIndexPath.item];
    //从资源数组中移除该数据
//    [self.resourceList removeObject:objc];
    //将数据插入到资源数组中的目标位置上
//    [self.resourceList insertObject:objc atIndex:destinationIndexPath.item];
    [self.resourceList exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
    if(self.resourceList.count) {
        self.albumModel.cover = [self.resourceList firstObject];
        self.albumModel.resourceList = [self.resourceList subarrayWithRange:NSMakeRange(1, self.resourceList.count-1)];
    } else {
        self.albumModel.resourceList = nil;
        self.albumModel.cover = nil;
    }
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BAResourceCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"BAResourceCell" forIndexPath:indexPath];
    BAAlbumItem *item ;
//    cell.indexPath = indexPath;
//    NSLog(@"%d",indexPath.row);

    if(indexPath.row == self.resourceList.count) {
        UIImage *image = [UIImage imageNamed:@"add_resource"];
        [cell setImage:image editMode:NO];
    } else {
        item = self.resourceList[indexPath.row];
        if(item.type == BAResourceTypeImage) {
            BAAlbumImageItem *imageItem = (BAAlbumImageItem *)item;
            [cell setImage:imageItem.image editMode:YES];
        } else {
            BAAlbumVideoItem *videoItem = (BAAlbumVideoItem *)item;
            [cell setImage:[videoItem.video getThumbnailImage] editMode:YES];
        }
        
        __weak typeof(cell) weakCell = cell;

        //删除操作
        [cell setDeleteBlock:^() {
            NSIndexPath *indexPath = [collectionView indexPathForCell:weakCell];
            [self.resourceList removeObjectAtIndex:indexPath.row];
            if(self.resourceList.count) {
                self.albumModel.cover = [self.resourceList firstObject];
                self.albumModel.resourceList = [self.resourceList subarrayWithRange:NSMakeRange(1, self.resourceList.count-1)];
            } else {
                self.albumModel.resourceList = nil;
                self.albumModel.cover = nil;
            }
            [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        }];
    }
    
   
    return cell;
    
}


- (void)reloadData {
    [self.collectionView reloadData];
}

- (void)didLoad {
    [super didLoad];
    
    self.backgroundColor = [UIColor clearColor];
    
    BAAlbumListLayout *layout = [[BAAlbumListLayout alloc] init];
    layout.numberOfColumns = 3;
    layout.headerHeight = 44;
    layout.footerHeight = [BAFooterView calculteHeightWithData:self.albumModel];
    
    
    self.collectionView = [[BACollectionView alloc] initWithFrame:CGRectMake(10, 0, kScreenWidth - 20, kScreenHeight - 64) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
//    self.collectionView.cornerRadius = 10;
    
//    [self.collectionView registerNib:[UINib nibWithNibName:@"BAFootView" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter  withReuseIdentifier:@"BAFootView"];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"BAFooterView" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"BAFooterView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"BAHeaderView" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BAHeaderView"];


//    [self.collectionView registerClass:[BAFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"BAFooterView"];

    [self.collectionView registerNib:[UINib nibWithNibName:@"BAResourceCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"BAResourceCell"];
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.collectionView addGestureRecognizer:self.longPress];
    [self.view addSubview:self.collectionView];

    
    
    
    self.resourceList = [NSMutableArray array];//WithArray:[self.albumModel fetchResourceList]];
    NSMutableArray *resourseList = [NSMutableArray arrayWithArray:[self.albumModel fetchResourceList]];
    //不存在封面 / 没有资源 / 相当于新建模式
    if(!self.albumModel.cover && resourseList.count) {
        self.albumModel.cover = [resourseList firstObject];
        [resourseList removeObjectAtIndex:0];
    } else if(self.albumModel.cover) {
        [self.resourceList addObject:self.albumModel.cover];
    }

    if(self.albumModel.album_id) {
        [self.resourceList addObjectsFromArray:resourseList];
    }
    
}

- (void)layout {
    [super layout];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.resourceList.count + _showAddButton ;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout originalItemSizeAtIndexPath:(NSIndexPath *)indexPath
{
    BAResourceCell *cellNode = (BAResourceCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    if ([cellNode isKindOfClass:[BAResourceCell class]]) {
//        CGSize size =  [(BAResourceCell *)cellNode calculatedSize];
        return CGSizeMake((kScreenWidth - 80)/3, (kScreenWidth - 80)/3);
    }
    return CGSizeMake(120, 120);
}

//- (CGSize)

//- (ASSizeRange)collectionView:(UICollectionView *)collectionView constrainedSizeForNodeAtIndexPath:(NSIndexPath *)indexPath
//{
//    BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
//    return ASSizeRangeMake(CGSizeZero, [layout itemSizeAtIndexPath:indexPath]);
//}



- (ASSizeRange)collectionView:(UICollectionView *)collectionView constrainedSizeForSupplementaryNodeOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if(kind == UICollectionElementKindSectionHeader) {
        BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
        return ASSizeRangeMake(CGSizeZero, [layout headerSizeForSection:indexPath.section]);
    } else if(kind == UICollectionElementKindSectionFooter) {
        BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
        return ASSizeRangeMake(CGSizeZero, [layout footerSizeForSection:indexPath.section]);
    }
    return ASSizeRangeMake(CGSizeZero, CGSizeZero);
;
}

- (ASScrollDirection)scrollableDirections
{
    return ASScrollDirectionVerticalDirections;
}

/**
 * Asks the inspector for the number of supplementary views for the given kind in the specified section.
 */
- (NSUInteger)collectionView:(UICollectionView *)collectionView supplementaryNodesOfKind:(NSString *)kind inSection:(NSUInteger)section
{
    return 1;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

    if(kind == UICollectionElementKindSectionFooter) {
        BAFooterView * footerView =[self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter  withReuseIdentifier:@"BAFooterView" forIndexPath:indexPath];
        [footerView setData:self.albumModel titleChangeBlock:^(NSString *text) {
            self.albumModel.title = text;
        } detailChangeBlock:^(NSString *text) {
            self.albumModel.desc = text;
        } datePickerBlock:^{
            // Picker Show 更新用户显示时间
            WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithStyle:DateStyleShowYearMonthDay defaultDate:[NSDate dateWithTimeIntervalSince1970:[self.albumModel.custom_date floatValue]] completeBlock:^(NSDate *startDate) {
                [self.footerView setDate:startDate];
                self.albumModel.custom_date = [startDate timeStampCurrentTime];
            }];
//            datepicker.scrollToDate = [NSDate dateWithTimeIntervalSinceNow:[self.albumModel.custom_date floatValue]];
            datepicker.maxLimitDate = [NSDate date];
            [datepicker show];
        }];
        self.footerView = footerView;
        return footerView;
    } else if(kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BAHeaderView" forIndexPath:indexPath];
        return headerView;
    }
    
    return [[UICollectionReusableView alloc] init] ;
}





//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    return nil;
//}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if(self.resourceList.count >= 20) {
        [MBProgressHUD showError:@"最多可添加20张"];
        return;
    }
    
    if(indexPath.row == self.resourceList.count) {
   
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
//        imagePicker.allowCrop = YES;
        [imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL isSelectOrigin) {
            if(photos.count) {
                BAAlbumImageItem *imageItem = [BAAlbumImageItem itemWithImage:[photos firstObject]];
                [self.resourceList addObject:imageItem];
                if(self.resourceList.count) {
                    self.albumModel.cover = [self.resourceList firstObject];
                    self.albumModel.resourceList = [self.resourceList subarrayWithRange:NSMakeRange(1, self.resourceList.count-1)];
                } else {
                    self.albumModel.resourceList = nil;
                    self.albumModel.cover = nil;
                }
                
                [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.resourceList.count - 1 inSection:0]]];
                if(self.resourceList.count >= 20) {
                    _showAddButton = NO;
                    [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.resourceList.count inSection:0]]];

                }

            }

        }];
        [imagePicker setDidFinishPickingVideoHandle:^(UIImage * image, id obj) {
            [self getVideoFromPHAsset:obj data:^(AVURLAsset *asset) {
                
                CMTime time = [asset duration];
                int seconds = ceil(time.value/time.timescale);
                if(seconds > 60) {
                    [MBProgressHUD showError:@"视频长度最大为60s"];
                }
                BAAlbumVideoItem *videoItem = [BAAlbumVideoItem itemWithVideoAsset:asset];
                [self.resourceList addObject:videoItem];
                if(self.resourceList.count) {
                    self.albumModel.cover = [self.resourceList firstObject];
                    self.albumModel.resourceList = [self.resourceList subarrayWithRange:NSMakeRange(1, self.resourceList.count-1)];
                } else {
                    self.albumModel.resourceList = nil;
                    self.albumModel.cover = nil;
                }
               
                [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.resourceList.count - 1 inSection:0]]];
                if(self.resourceList.count >= 20) {
                    _showAddButton = NO;
                    [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.resourceList.count inSection:0]]];

                }
            }];
        }];
        
        [KEYWINDOW.rootViewController presentViewController:imagePicker animated:YES completion:nil];
    }
    
    
}


- (void)editableTextNodeDidUpdateText:(ASEditableTextNode *)editableTextNode {
    self.albumModel.title = editableTextNode.textView.text;
}


#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    [self.view endEditing:YES];
//}

- (void)showPhotoBrowerWithIndex:(NSInteger)index {
    // Create array of MWPhoto objects
    self.photos = [NSMutableArray array];
    
    for(BAAlbumItem *item in self.resourceList) {
        if(item.type == BAResourceTypeImage) {
            BAAlbumImageItem *imageItem = (BAAlbumImageItem *)item;
            [self.photos addObject:[MWPhoto photoWithImage:imageItem.image]];
        } else if(item.type == BAResourceTypeVideo) {
            BAAlbumVideoItem *videoItem = (BAAlbumVideoItem *)item;
            
            [self.photos addObject:[MWPhoto videoWithURL:videoItem.video.URL]];
        }
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    
    // Set options
    browser.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    browser.autoPlayOnAppear = NO; // Auto-play first video
    
    // Customise selection images to change colours if required
    browser.customImageSelectedIconName = @"ImageSelected.png";
    browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
    
    // Optionally set the current visible photo before displaying
    [browser setCurrentPhotoIndex:index];
    
    // Present
    [self.manager.navigationController pushViewController:browser animated:YES];
    
    // Manipulate
    [browser showNextPhotoAnimated:YES];
    [browser showPreviousPhotoAnimated:YES];
    //    [browser setCurrentPhotoIndex:10];
}


- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}

- (void)getVideoFromPHAsset:(PHAsset *)asset data:(void (^)(AVURLAsset *asset))block {
    PHVideoRequestOptions *option = [PHVideoRequestOptions new];
    
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:option resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            AVURLAsset * ass= (AVURLAsset *)asset;
            block(ass);
        });
    }];
}

//- (void)datePickerValueChanged:(UIDatePicker *)picker {
//    NSDate *date = [picker date];
//    self.footerNode.
//}



@end
